how to use OmitType from nestjs swagger
AI Response
OmitType from @nestjs/swagger is a utility function that allows you to create a new DTO (Data Transfer Object) by omitting specific properties from an existing DTO class.
Usage of OmitType
The OmitType function is useful when you want to create a subset of an existing DTO while excluding certain fields, particularly in request DTOs where some properties (e.g., id, createdAt, etc.) should not be included in user input.
Syntax
import { OmitType } from '@nestjs/swagger';
class BaseDto {
id: number;
createdAt: Date;
updatedAt: Date;
name: string;
email: string;
}
class CreateUserDto extends OmitType(BaseDto, ['id', 'createdAt', 'updatedAt']) {}
Example Use Cases
1. Creating a DTO for a Create API
You might have a UserDto that represents a full user object with properties like id, createdAt, and updatedAt. However, when a user is being created, these fields should not be included in the request.
import { OmitType } from '@nestjs/swagger';
class UserDto {
id: number;
createdAt: Date;
updatedAt: Date;
name: string;
email: string;
}
export class CreateUserDto extends OmitType(UserDto, ['id', 'createdAt', 'updatedAt']) {}
Here, CreateUserDto will only contain name and email properties.
2. Creating an Update DTO
For an update operation, you might want to allow only partial updates, omitting fields like id.
import { PartialType, OmitType } from '@nestjs/swagger';
class UserDto {
id: number;
name: string;
email: string;
createdAt: Date;
updatedAt: Date;
}
export class UpdateUserDto extends PartialType(OmitType(UserDto, ['id', 'createdAt', 'updatedAt'])) {}
-
OmitType(UserDto, ['id', 'createdAt', 'updatedAt']): Removes id, createdAt, and updatedAt.
-
PartialType(...): Makes all properties optional.
Your Code Example
In your file action-required.dto.ts, you used OmitType like this:
export class ActionRequiredLogDtoRequest extends OmitType<
ActionRequiredLogDto,
['createdTime']
> {}
This means ActionRequiredLogDtoRequest will inherit all properties from ActionRequiredLogDto, except createdTime, making it useful for request payloads where createdTime should not be provided.
Key Takeaways
-
OmitType(BaseDto, ['prop1', 'prop2']): Creates a DTO without specified properties.
-
Common Use Cases:
-
Create DTOs (omit id, createdAt, updatedAt).
-
Update DTOs (omit id, use PartialType for optional fields).
- Used in NestJS Swagger for API documentation.